<template>
  <div class="container" style="width:100%;height:100%;background:#f3f3f3;">
    <van-nav-bar :title="title" fixed class="titleStyle" left-arrow @click-left="onClickLeft" />
    <div class="searchDiv">
      <form action="/">
        <van-search v-model="search.reworkNo" show-action placeholder="请输入返工返修单号进行搜索" @search="onSearch" @cancel="onCancel" />
      </form>
      <van-button class="saveBtns" type="primary" native-type="submit" @click="onSearch(search.reworkNo)">查询</van-button>
    </div>
    <!-- 报废单-->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="已全部加载完成" class="van-clearfix" :immediate-check="false" @load="onLoad">
        <div class="contentBox" style="padding: 120px 10px 180px 10px;">
          <div v-for=" item in list" :key="item.purchaseId" class="listDiv">
            <van-row style="width:100%;height:100%;">
              <div class="checkList">
                <!-- <h1>
                  <span>{{ item.bfdh }}</span>
                  <b>报废单号</b>
                </h1>-->
                <ul>
                  <li>
                    <b>返工返修卡</b>
                    <span>{{item.planBatchNo}}</span>
                  </li>
                  <li>
                    <b>工单批次号：</b>
                    <span>{{ item.originalPlanBatchNo }}</span>
                  </li>
                  <li>
                    <b>返工返修单：</b>
                    <span>{{ item.reworkNo }}</span>
                  </li>
                  <li>
                    <b>料号：</b>
                    <span>{{ item.materialCode }}</span>
                  </li>
                  <li>
                    <b>品名：</b>
                    <span>{{ item.materialName }}</span>
                  </li>
                  <li>
                    <b>产品规格：</b>
                    <span>{{ item.specifications }}</span>
                  </li>
                  <li>
                    <b>产线：</b>
                    <span>{{ item.factoryName }}</span>
                  </li>
                  <li>
                    <b>检验人：</b>
                    <span>{{ item.createName }}</span>
                  </li>
                  <li>
                    <b>断点工序：</b>
                    <span>{{ item.procedureName }}</span>
                  </li>
                  <li>
                    <b>缺陷项：</b>
                    <span>{{ item.defectName }}</span>
                  </li>
                  <li>
                    <b>派工数：</b>
                    <span>{{ item.releasedNum }}</span>
                  </li>
                  <li>
                    <b>派工时间：</b>
                    <span>{{ item.workTime }}</span>
                  </li>
                  <li>
                    <b>检验时间：</b>
                    <span>{{ item.createAt }}</span>
                  </li>
                </ul>
                <div class="checkListBtn">
                  <van-button type="info" @click="printBtn(item)">打印</van-button>
                </div>
              </div>
            </van-row>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
    <div v-show="list.length === 0 && loading === false" class="noDataAvailable noDataAvailable3" />
    <van-popup v-model="printShow" closeable position="bottom" :style="{ height: '20%' }">
      <div class="printDiv">
        <van-button type="info" size="small" native-type="button" @click="printLabel(1)">
          <i class="fa fa-bluetooth" style="margin-right: 5px"></i>蓝牙打印
        </van-button>
        <van-button type="info" size="small" icon="exchange" native-type="button" @click="printLabel(2)">切换打印机</van-button>
        <print :printValue="printValue" :address="address" :showPrint="showPrint" @closePrint="closePrint"></print>
        <!-- <van-overlay :show="loading">
          <van-loading color="#1989fa" v-if="loading" />
        </van-overlay>-->
      </div>
    </van-popup>
  </div>
</template>
<script>
import Print from '../component/BluetoothMatch.vue'
import { bluetoothPrint } from '@/utils/bluetoothPrint'
export default {
  components: {
    Print
  },
  name: 'FirstInspection',
  data() {
    return {
      showPrint: false,
      printValue: [],
      address: '',
      printShow: false,
      show: false,
      title: localStorage.getItem('name'),
      code: localStorage.getItem('code'),
      search: {
        reworkNo: '',
        current: 1,
        size: 5
      },
      list: [],
      pages: 0,
      total: 0,
      loading: false,
      finished: false,
      isLoading: false,
      listPro: [], // 打印行工序列表
      printInfo: {} // 打印行信息
    }
  },
  created() {
    this.search.reworkNo = this.$route.query.code
  },
  mounted() {
    this.getListInfo()
  },
  methods: {
    onSearch(val) {
      this.search.reworkNo = val
      this.getListInfo(1)
    },
    onCancel() {
      this.search.reworkNo = ''
      this.finished = false
      this.getListInfo(1)
    },
    /* 获取页面数据 */
    async getListInfo(page) {
      if (page) this.search.current = page
      if (+page === 1) this.list = []
      this.loading = true
      const res = await this.$axios.post(
        '/dobo-product/web/quarantine/record/recordCarPage',
        this.search
      )
      if (res.data.code === 200) {
        this.show = false
        const list = []
        res.data.data.list.filter((item) => {
          list.push(item)
        })
        this.list = this.list.concat(list) // 去重 合并
        const hash = {}
        // 数组去重
        this.list = this.list.reduce((preVal, curVal) => {
          /* eslint-disable-next-line */
          hash[curVal.quarantineManagementRecordId]
            ? ''
            : (hash[curVal.quarantineManagementRecordId] =
                true && preVal.push(curVal))
          return preVal
        }, [])
        this.total = res.data.data.total
        this.loading = false
        if (+this.list.length === +this.total) {
          this.finished = true
        }
      }
    },
    //   触底加载
    onLoad() {
      setTimeout(() => {
        if (this.list.length < this.search.current) {
          this.finished = true
          return
        }

        if (this.list.length === this.total) {
          this.finished = true
          return
        }
        let num
        num = this.search.current
        num++
        this.getListInfo(num)
      }, 1000)
    },
    //  下拉刷新
    onRefresh() {
      setTimeout(() => {
        this.list = []
        this.total = 0
        this.finished = false
        this.getListInfo(1)
        this.isLoading = false
      }, 500)
    },
    /* 打印 */
    printBtn(row) {
      const { procedureList } = row
      console.log(procedureList)
      this.listPro = procedureList
      this.printInfo = row
      this.printShow = true
    },
    printLabel(type) {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '打印中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      setTimeout(() => {
        toast.clear()
        this.printByBluetooth(type)
      }, 500)
    },

    closePrint() {
      this.showPrint = false
    },
    printByBluetooth(type) {
      let strList = []
      let boxTopNum = 180
      let boxBottomNum = 230
      let fontTopNum = 0
      let allNum = 0
      // 遍历工序
      this.listPro.forEach((item) => {
        boxTopNum = boxTopNum + 48
        boxBottomNum = boxTopNum + 50
        fontTopNum = boxTopNum + 10
        item.str = ''
        item.str += `BOX 20 ${boxTopNum} 90 ${boxBottomNum} 1` + '\r\n'
        item.str += `TEXT GBUNSG24.CPF 0 23 ${fontTopNum} ${item.sort}` + '\r\n'
        item.str += `BOX 90 ${boxTopNum} 330 ${boxBottomNum} 1` + '\r\n'
        item.str +=
          `TEXT GBUNSG24.CPF 0 95 ${fontTopNum} ${item.procedureName}` + '\r\n'

        item.str += `BOX 330 ${boxTopNum} 430 ${boxBottomNum} 1` + '\r\n'
        item.str += `TEXT GBUNSG24.CPF 0 335 ${fontTopNum} ` + '\r\n'
        item.str += `BOX 430 ${boxTopNum} 560 ${boxBottomNum} 1` + '\r\n'
        item.str += `TEXT GBUNSG24.CPF 0 435 ${fontTopNum} ` + '\r\n'
        strList.push(item.str)
        allNum = boxBottomNum
      })
      let strs = strList.reduce((result, element) => {
        return result + element.toString()
      }, '')
      this.printValue = []
      // 标签开始, 固定开头, 详见 指令集文档
      let str = `! 0 200 200 ${allNum + 55} 1 ` + '\r\n'
      // 设置打印纸张宽度
      str += 'PAGE-WIDTH 700' + '\r\n'
      str += 'TEXT GBUNSG24.CPF 0 250 0 返工返修流程卡' + '\r\n'
      //二维码和单号
      str += 'B QR 20 40 M 2 U 5' + '\r\n'
      str += `MA,QR code ${this.printInfo.planBatchNo}` + '\r\n'
      str += 'ENDQR' + '\r\n'
      str +=
        `TEXT GBUNSG24.CPF 0 155 30 卡号:${this.printInfo.planBatchNo}` + '\r\n'
      str +=
        `TEXT GBUNSG24.CPF 0 155 60 品名:${this.printInfo.materialName}` +
        '\r\n'
      str +=
        `TEXT GBUNSG24.CPF 0 155 90 料号:${this.printInfo.materialCode}` +
        '\r\n'
      str +=
        `TEXT GBUNSG24.CPF 0 155 120 规格:${this.printInfo.specifications}` +
        '\r\n'
      str +=
        `TEXT GBUNSG24.CPF 0 155 150 断点工序:${this.printInfo.procedureName}` +
        '\r\n'

      str += 'BOX 20 180 90 230 1' + '\r\n'
      str += 'TEXT GBUNSG24.CPF 0 23 190 序号' + '\r\n'
      str += 'BOX 90 180 330 230 1' + '\r\n'
      str += `TEXT GBUNSG24.CPF 0 95 190 工序` + '\r\n'

      str += 'BOX 330 180 430 230 1' + '\r\n'
      str += 'TEXT GBUNSG24.CPF 0 335 190 在制数' + '\r\n'
      str += 'BOX 430 180 560 230 1' + '\r\n'
      str += `TEXT GBUNSG24.CPF 0 435 190 完工数` + '\r\n' + strs

      str += 'PRINT' + '\r\n'
      console.log(str)
      setTimeout(() => {
        this.printValue.push(str)
        if (type == 1) {
          //蓝牙打印
          let lastConnectAddress = ''
          if (localStorage.getItem('lastConnectAddress')) {
            //默认取上次连接的打印机
            lastConnectAddress = localStorage.getItem('lastConnectAddress')
          }
          if (lastConnectAddress) {
            //直接连接第一个
            bluetoothPrint(lastConnectAddress, this.printValue)
          } else {
            this.$toast('请选择打印机')
          }
        } else {
          //切换打印机
          this.showPrint = true
        }
      }, 1000)
    },
    // 返回
    onClickLeft() {
      this.$router.push('/Task')
    }
  }
}
</script>
<style lang='scss' scoped>
.printDiv {
  padding: 50px 0 0 20px;
  text-align: center;
}
.van-button--small {
  width: 130px;
  height: 80px;
  margin-right: 10px;
  font-size: 16px;
}
.searchDiv {
  width: 100%;
  height: 52px;
  position: fixed;
  top: 60px;
  z-index: 99;
  background: #fff;
  .van-search {
    width: calc(100% - 100px);
  }
  .saveBtns {
    position: fixed;
    top: 68px;
    right: 10px;
    font-size: 14px;
    height: 32px;
    line-height: 32px;
    background: linear-gradient(to top right, #1cacff, #022566);
    border: 1px solid #022566;
    .van-button__content {
      display: block;
      .van-button__text {
        text-align: center;
        width: 100%;
        font-size: 20px;
      }
    }
  }
}
</style>
<style lang='scss'>
</style>
